﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Xml;

namespace Survey.Models
{
    public class XmlSurveyRetrieverModel : ISurveyRetrieverModel
    {
        private SurveyModel _survey;

        /// <summary>
        /// Default constructor
        /// </summary>
        public XmlSurveyRetrieverModel() { }       

        /// <summary>
        /// The survey for this model
        /// </summary>
        public SurveyModel Survey
        {
            get
            {
                return _survey;
            }
            private set
            {
                //Check the reference
                if (_survey == value) return;

                _survey = value;
                OnPropertyChanged("Survey");
            }
        }

        /// <inheritdoc />
        public void PopulateSurvey()
        {
            //TODO: Check file exists   
            try
            {
                var serializer = new XmlSerializer(typeof(SurveyModel));
            
                //Must be the property which is set to fire the property changed event
                //TODO: Can we be more flexible with this xml file, e.g. filenames?
                Survey = (SurveyModel)serializer.Deserialize(XmlReader.Create("SurveyModel.xml"));
            }
            catch (Exception e)
            {
                //TODO: Do something useful
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {

            if (PropertyChanged != null)

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        }

        #endregion
    }
}
